var $$ = function(id){return document.getElementById(id);};
var ws = new WebSocket('wss://static.zhouchun.net/view');
var yourUsernameInput = $$('yourUsername');
var otherUsernameInput = $$('otherUsername');
var yourVideo = $$('your');
var otherVideo = $$('other');
var yourUsername = '';
var otherUsername = '';
var loginButton = $$('login');
var callButton = $$('call');
var leaveButton = $$('leave');
var viewer = $$('viewer');
var yourConnection;
var stream;

ws.onopen = function(){
    console.log('[onopen]连接成功');
};

ws.onerror = function(error){
    console.log('[onerror]发生错误:', error);
};

ws.onmessage = function(message){
    console.log('[onmessage]', message.data);
    var data = JSON.parse(message.data);
    switch(data.type){
        case 'login':
            onLogin(data);
            break;
        case 'offer':
            onOffer(data);
            break;
        case 'answer':
            onAnswer(data);
            break;
        case 'candidate':
            onCandidate(data);
            break;
        case 'leave':
            onLeave(data);
            break;
        default:
            break;
    }
};

function send(message){
    ws.send(JSON.stringify(message));
}

loginButton.addEventListener("click", function(event){
    yourUsername = yourUsernameInput.value;
    if(yourUsername.length > 0){
        send({type: "login", yourUsername: yourUsername, otherUsername: otherUsername});
    }
});

callButton.addEventListener("click", function(){
    otherUsername = otherUsernameInput.value;
    if(otherUsername.length > 0){
        startPeerConnection(otherUsername);
    }
});

leaveButton.addEventListener("click", function(){
    send({type: "leave", yourUsername: yourUsername, otherUsername: otherUsername});
    onLeave();
});

function onLogin(data){
    if(data.success == '0'){
        alert("请输入另一个用户名");
    }
    else{
        startConnection();
    }
}

function onOffer(data){
    otherUsername = data.otherUsername;
    yourConnection.setRemoteDescription(new RTCSessionDescription(data.offer));
    yourConnection.createAnswer(
        function(answer){
            yourConnection.setLocalDescription(answer);
            send({type: "answer", answer: answer, yourUsername: yourUsername, otherUsername: otherUsername});
        },
        function(error){
            alert("[onOffer]error");
        }
    );
}

function onAnswer(data){
    yourConnection.setRemoteDescription(new RTCSessionDescription(data.answer));
}

function onCandidate(data){
    yourConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
}

function onLeave(){
    otherUsername = null;
    otherVideo.src = null;
    yourConnection.close();
    yourConnection.onicecandidate = null;
    yourConnection.onaddstream = null;
    setupPeerConnection(stream);
}

function startConnection(){
    if(viewer.checked){
        stream = document.getElementById("canvas").captureStream(1);
        setupPeerConnection(stream);
    }
    else{
        var rate = $$("rate").value;
        var resolution = $$("resolution").value.split("*");
        var width = resolution[0];
        var height = resolution[1];
        var constraints = {
            audio: false,
            video: {
                width: {
                    min: width,
                    max: width,
                    ideal: width
                },
                height: {
                    min: height,
                    max: height,
                    ideal: height
                },
                frameRate: {
                    min: rate,
                    max: rate,
                    ideal: rate
                }
            }
        };
        navigator.mediaDevices.getUserMedia(constraints)
        .then(function(theStream){
            stream = theStream;
            if(! $$("showSelf").checked){
                yourVideo.src = window.URL.createObjectURL(stream);
            }
            setupPeerConnection(stream);
        })
        .catch(function(error){
            console.log(error);
        });
    }
}

function setupPeerConnection(stream){
    var configuration = {"iceServers": [{"url": "turn:106.75.15.228:3478", "username": "ling", "credential": "ling1234"}]};
    yourConnection = new RTCPeerConnection(configuration);
    if(stream){
        yourConnection.addStream(stream);
    }
    yourConnection.onaddstream = function(e){
        otherVideo.src = window.URL.createObjectURL(e.stream);
    };
    yourConnection.onicecandidate = function(event){
        if(event.candidate){
            send({type: "candidate", candidate: event.candidate, yourUsername: yourUsername, otherUsername: otherUsername});
        }
    };
    yourConnection.oniceconnectionstatechange = function(event){
        /*
        failed|disconnected|closed
        */
        console.log(yourConnection.iceConnectionState);
        console.log(event);
    };
}

function startPeerConnection(otherUsername){
    otherUsername = otherUsername;
    yourConnection.createOffer(
        function(offer){
            console.log('send offer');
            send({type: "offer", offer: offer, yourUsername: yourUsername, otherUsername: otherUsername});
            yourConnection.setLocalDescription(offer);
        },
        function(error){
            alert(error);
        }
    );
}
